<template>
  <div class="business-chart-container">
    <el-card class="chart-card" v-loading="loading">
      <div class="chart-header">
        <h2>{{ $t("common.businessChart") }}</h2>
        <el-button type="primary" size="small" icon="el-icon-refresh" @click="refreshData">
        </el-button>
      </div>
      <div id="businessChart" class="chart-content"></div>
    </el-card>
  </div>
</template>

<script>
import { bussiness } from '@/api/system/order'
import * as echarts from 'echarts'
import {getUserProfile} from '@/api/system/user'

export default {
  data() {
    return {
      chart: null,
      loading: false,
      chartOption: {
        backgroundColor: '#ffffff',
        title: {
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#ccc',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          },
          formatter: function(params) {
            let result = `<div style="font-weight: bold; margin-bottom: 5px">${params[0].name}</div>`;
            params.forEach(param => {
              const currency = param.seriesName;
              let prefix = '';

              // 根据货币类型设置前缀
              if (currency === 'JPY' || currency === '日元') {
                prefix = 'jpy';
              } else if (currency === 'CNY' || currency === '人民币') {
                prefix = 'rmb';
              } else if (currency === 'TWD' || currency === '台币') {
                prefix = 'twd';
              }

              const itemData = param.data;
              result += `
                <div style="display: flex; justify-content: space-between; margin: 3px 0">
                  <span style="margin-right: 15px">${param.seriesName}:</span>
                  <span style="font-weight: bold">${param.value.toLocaleString()}</span>
                </div>`;

              // 获取该部门的完整数据
              const deptData = data.find(item => item.deptName === params[0].name);
              if (deptData) {
                // 添加费用明细
                if (prefix === 'jpy') {
                  result += `
                    <div style="margin-top: 5px; border-top: 1px dashed #ddd; padding-top: 5px;">
                      <div style="font-size: 12px; color: #666;">订单费用: ${deptData.jpyCostAmount ? deptData.jpyCostAmount.toLocaleString() : 0}</div>
                      <div style="font-size: 12px; color: #666;">加收费用: ${deptData.jpyAddSubMoneyAmount ? deptData.jpyAddSubMoneyAmount.toLocaleString() : 0}</div>
                      ${deptData.allFlag ? `<div style="font-size: 12px; color: #666;">拆壳费用: ${deptData.jpyRemoveBoxAmount ? deptData.jpyRemoveBoxAmount.toLocaleString() : 0}</div>
                      <div style="font-size: 12px; color: #666;">贩卖佣金: ${deptData.jpySaleAmount ? deptData.jpySaleAmount.toLocaleString() : 0}</div>` : ''}
                    </div>
                  `;
                } else if (prefix === 'rmb') {
                  result += `
                    <div style="margin-top: 5px; border-top: 1px dashed #ddd; padding-top: 5px;">
                      <div style="font-size: 12px; color: #666;">订单费用: ${deptData.rmbCostAmount ? deptData.rmbCostAmount.toLocaleString() : 0}</div>
                      <div style="font-size: 12px; color: #666;">加收费用: ${deptData.rmbAddSubMoneyAmount ? deptData.rmbAddSubMoneyAmount.toLocaleString() : 0}</div>
                      ${deptData.allFlag ? `<div style="font-size: 12px; color: #666;">拆壳费用: ${deptData.rmbRemoveBoxAmount ? deptData.rmbRemoveBoxAmount.toLocaleString() : 0}</div>
                      <div style="font-size: 12px; color: #666;">贩卖佣金: ${deptData.rmbSaleAmount ? deptData.rmbSaleAmount.toLocaleString() : 0}</div>` : ''}
                    </div>
                  `;
                } else if (prefix === 'twd') {
                  result += `
                    <div style="margin-top: 5px; border-top: 1px dashed #ddd; padding-top: 5px;">
                      <div style="font-size: 12px; color: #666;">订单费用: ${deptData.twdCostAmount ? deptData.twdCostAmount.toLocaleString() : 0}</div>
                      <div style="font-size: 12px; color: #666;">加收费用: ${deptData.twdAddSubMoneyAmount ? deptData.twdAddSubMoneyAmount.toLocaleString() : 0}</div>
                      ${deptData.allFlag ? `<div style="font-size: 12px; color: #666;">拆壳费用: ${deptData.twdRemoveBoxAmount ? deptData.twdRemoveBoxAmount.toLocaleString() : 0}</div>
                      <div style="font-size: 12px; color: #666;">贩卖佣金: ${deptData.twdSaleAmount ? deptData.twdSaleAmount.toLocaleString() : 0}</div>` : ''}
                    </div>
                  `;
                }
              }
            });
            return result;
          }
        },
        legend: {
          top: 30,
          textStyle: {
            fontSize: 12
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            interval: 0,
            rotate: 30,
            textStyle: {
              fontSize: 12
            }
          },
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        }
      }
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    async initChart() {
      await this.getUserProfile()
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    },
    refreshData() {
      this.getUserProfile()
    },
    async init(origin) {
      this.loading = true
      try {
        const res = await bussiness()
        console.log(res.data);
        const data = res.data
        this.renderChart(data, origin)
      } catch (error) {
        console.error('Failed to fetch business data:', error)
        this.$message.error(this.$t('common.fetchDataError'))
      } finally {
        this.loading = false
      }
    },
    renderChart(data, origin) {
      const chartDom = document.getElementById('businessChart')
      if (this.chart) {
        this.chart.dispose()
      }
      this.chart = echarts.init(chartDom)

      // 创建数据对象数组用于排序
      const sortableData = data.map(item => ({
        name: item.deptName,
        allFlag: item.allFlag,
        jpyAmount: item.jpyAmount || 0,
        rmbAmount: item.rmbAmount || 0,
        twdAmount: item.twdAmount || 0,
        // 添加所有费用明细数据
        jpyAddSubMoneyAmount: item.jpyAddSubMoneyAmount || 0,
        jpyCostAmount: item.jpyCostAmount || 0,
        jpyRemoveBoxAmount: item.jpyRemoveBoxAmount || 0,
        jpySaleAmount: item.jpySaleAmount || 0,
        rmbAddSubMoneyAmount: item.rmbAddSubMoneyAmount || 0,
        rmbCostAmount: item.rmbCostAmount || 0,
        rmbRemoveBoxAmount: item.rmbRemoveBoxAmount || 0,
        rmbSaleAmount: item.rmbSaleAmount || 0,
        twdAddSubMoneyAmount: item.twdAddSubMoneyAmount || 0,
        twdCostAmount: item.twdCostAmount || 0,
        twdRemoveBoxAmount: item.twdRemoveBoxAmount || 0,
        twdSaleAmount: item.twdSaleAmount || 0
      }))

      // 按日元金额从大到小排序
      sortableData.sort((a, b) => b.jpyAmount - a.jpyAmount)

      // 提取排序后的店名
      const sortedXData = sortableData.map(item => item.name)
      let series = []
      let legend = []

      const colors = {
        cny: '#409EFF',
        jpy: '#67C23A',
        twd: '#E6A23C'
      }

      // 根据origin选择对应的金额组合
      switch(origin) {
        case "1":
          legend = [this.$t("common.cny"), this.$t("common.jpy")]
          series = this.createSeries([
            { name: this.$t("common.cny"), data: sortableData.map(item => item.rmbAmount), color: colors.cny },
            { name: this.$t("common.jpy"), data: sortableData.map(item => item.jpyAmount), color: colors.jpy }
          ])
          break
        case "2":
          legend = [this.$t("common.twd"), this.$t("common.jpy")]
          series = this.createSeries([
            { name: this.$t("common.twd"), data: sortableData.map(item => item.twdAmount), color: colors.twd },
            { name: this.$t("common.jpy"), data: sortableData.map(item => item.jpyAmount), color: colors.jpy }
          ])
          break
        case "3":
          legend = [this.$t("common.jpy")]
          series = this.createSeries([
            { name: this.$t("common.jpy"), data: sortableData.map(item => item.jpyAmount), color: colors.jpy }
          ])
          break
      }

      const option = {
        ...this.chartOption,
        legend: {
          ...this.chartOption.legend,
          data: legend
        },
        xAxis: {
          ...this.chartOption.xAxis,
          data: sortedXData
        },
        series,
        tooltip: {
          ...this.chartOption.tooltip,
          formatter: (params) => {
            let result = `<div style="font-weight: bold; margin-bottom: 5px">${params[0].name}</div>`;
            params.forEach(param => {
              const currency = param.seriesName;
              let prefix = '';

              // 根据货币类型设置前缀
              if (currency === this.$t("common.jpy")) {
                prefix = 'jpy';
              } else if (currency === this.$t("common.cny")) {
                prefix = 'rmb';
              } else if (currency === this.$t("common.twd")) {
                prefix = 'twd';
              }

              result += `
                <div style="display: flex; justify-content: space-between; margin: 3px 0">
                  <span style="margin-right: 15px">${param.seriesName}:</span>
                  <span style="font-weight: bold">${param.value.toLocaleString()}</span>
                </div>`;

              // 获取该部门的完整数据
              const deptData = sortableData.find(item => item.name === params[0].name);
              if (deptData) {
                // 添加费用明细
                if (prefix === 'jpy') {
                  result += `
                    <div style="margin-top: 5px; border-top: 1px dashed #ddd; padding-top: 5px;">
                      <div style="font-size: 12px; color: #666;">${this.$t("business.orderCost")}: ${deptData.jpyCostAmount ? deptData.jpyCostAmount.toLocaleString() : 0}</div>
                      <div style="font-size: 12px; color: #666;">${this.$t("business.addSubMoney")}: ${deptData.jpyAddSubMoneyAmount ? deptData.jpyAddSubMoneyAmount.toLocaleString() : 0}</div>
                      ${deptData.allFlag ? `<div style="font-size: 12px; color: #666;">${this.$t("business.removeBox")}: ${deptData.jpyRemoveBoxAmount ? deptData.jpyRemoveBoxAmount.toLocaleString() : 0}</div>
                      <div style="font-size: 12px; color: #666;">${this.$t("business.saleAmount")}: ${deptData.jpySaleAmount ? deptData.jpySaleAmount.toLocaleString() : 0}</div>` : ''}
                    </div>
                  `;
                } else if (prefix === 'rmb') {
                  result += `
                    <div style="margin-top: 5px; border-top: 1px dashed #ddd; padding-top: 5px;">
                      <div style="font-size: 12px; color: #666;">${this.$t("business.orderCost")}: ${deptData.rmbCostAmount ? deptData.rmbCostAmount.toLocaleString() : 0}</div>
                      <div style="font-size: 12px; color: #666;">${this.$t("business.addSubMoney")}: ${deptData.rmbAddSubMoneyAmount ? deptData.rmbAddSubMoneyAmount.toLocaleString() : 0}</div>
                      ${deptData.allFlag ? `<div style="font-size: 12px; color: #666;">${this.$t("business.removeBox")}: ${deptData.rmbRemoveBoxAmount ? deptData.rmbRemoveBoxAmount.toLocaleString() : 0}</div>
                      <div style="font-size: 12px; color: #666;">${this.$t("business.saleAmount")}: ${deptData.rmbSaleAmount ? deptData.rmbSaleAmount.toLocaleString() : 0}</div>` : ''}
                    </div>
                  `;
                } else if (prefix === 'twd') {
                  result += `
                    <div style="margin-top: 5px; border-top: 1px dashed #ddd; padding-top: 5px;">
                      <div style="font-size: 12px; color: #666;">${this.$t("business.orderCost")}: ${deptData.twdCostAmount ? deptData.twdCostAmount.toLocaleString() : 0}</div>
                      <div style="font-size: 12px; color: #666;">${this.$t("business.addSubMoney")}: ${deptData.twdAddSubMoneyAmount ? deptData.twdAddSubMoneyAmount.toLocaleString() : 0}</div>
                      ${deptData.allFlag ? `<div style="font-size: 12px; color: #666;">${this.$t("business.removeBox")}: ${deptData.twdRemoveBoxAmount ? deptData.twdRemoveBoxAmount.toLocaleString() : 0}</div>
                      <div style="font-size: 12px; color: #666;">${this.$t("business.saleAmount")}: ${deptData.twdSaleAmount ? deptData.twdSaleAmount.toLocaleString() : 0}</div>` : ''}
                    </div>
                  `;
                }
              }
            });
            return result;
          }
        }
      }

      this.chart.setOption(option)
    },
    createSeries(items) {
      return items.map(({ name, data, color }) => ({
        name,
        data,
        type: 'bar',
        barWidth: items.length > 1 ? '20%' : '40%',
        itemStyle: {
          color,
          borderRadius: [4, 4, 0, 0]
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}',
          fontSize: 12,
          color: '#666'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }))
    },
    async getUserProfile() {
      try {
        const res = await getUserProfile()
        const origin = res.data.origin
        await this.init(origin)
      } catch (error) {
        console.error('Failed to fetch user profile:', error)
        this.$message.error(this.$t('common.fetchDataError'))
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.business-chart-container {
  padding: 20px;

  .chart-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding: 0 20px;

      h2 {
        margin: 0;
        font-size: 18px;
        color: #303133;
      }
    }

    .chart-content {
      width: 100%;
      height: 400px;
      position: relative;
    }
  }
}
</style>
